import qs from 'qs';
import Moment from 'moment';
import _ from 'lodash';
import { api3th } from '../Axios/api3th';

export default {
  namespaced: true,
  state: {
    _cname: '股票对象',
    code: null,
    klineParmas: {
      // 参考啊api3th.md
      get_type: ['offset', 'range'][1],
      prod_code: '',
      candle_period: [1, 2, 3, 4, 5, 6, 7, 8, 9][5], //默认日线
      fields: null, //使用默认，传参前过滤
      search_direction: null,
      data: null,
      min_time: null,
      data_count: null,
      start_date: null,
      end_date: null,
    },
    linedata: [],
    // prettier-ignore
    RULE: [
      ['min_time','分时分钟时间(HHMM)','timestamp','时间戳，毫秒级别，必要字段'],
      ['open_px', '开盘价', 'open', '开盘价，必要字段'],
      ['high_px', '最高价', 'high', '最高价，必要字段'],
      ['low_px', '最低价', 'low', '最低价，必要字段'],
      ['close_px', '收盘价', 'close', ' 收盘价，必要字段'],
      ['business_amount', '成交数量', 'volume', '成交量，非必须字段'], //
      ['business_balance','成交金额','turnover',"成交额，非必须字段，如果需要展示技术指标'EMV'和'AVP'，则需要为该字段填充数据。",],
      // ['turnover_ratio',''],//换手率
      // ['preclose_px',''],//昨收价
    ],
    // prettier-ignore
    realInfo: {
      prod_name: '', //股票名称
      open_px: 0, //开盘
      preclose_px: 0, //收盘
      high_px: 0, //最高
      low_px: 0, //最低
      business_balance: 0, //成交金额
      turnover_ratio: 0, //换手率
      last_px: 0, //最新价
      px_change: 0, //价格涨跌
      px_change_rate: 0, //涨跌幅
    }
  },
  mutations: {
    setKeyValue: function(state, { key, value }) {
      console.log(key, value);
      state[key] = value;
    },
    getUrlArgs: function(state, { keyName }) {
      let wl = window.location;
      let search = wl.search == '' ? wl.hash.split('?')[1] : wl.search;
      let sc = qs.parse(search, {
        ignoreQueryPrefix: true,
      });
      let key = keyName || 'SC';
      state.klineParmas.prod_code = sc[key];
    },
    setKlineParmas: function(ctx, obj) {
      Object.assign(ctx.klineParmas, obj);
    },
    setLineData: function(state, linedata) {
      let tar = state.linedata;
      tar.splice(0, tar.lenght);
      tar.push(...linedata);
    },
    setHsDataFormatted: function(state, { hsData, params }) {
      let tar = state.linedata;
      tar.splice(0, tar.lenght);
      const RULE = state.RULE;
      hsData.forEach((item) => {
        let obj = {};
        RULE.forEach((v, i, a) => {
          let key = v[2];
          let value = item[i]; //该方法对应恒生接口使用
          if (key == 'timestamp') {
            switch (params.candle_period) {
              case 1:
                value = Moment(value, 'YYYYMMDDhhmm').valueOf();
                break;
              case 6:
              case 7:
              case 8:
              case 9:
                value = Moment(value, 'YYYYMMDD').valueOf();
                break;
              default:
                value = Moment(value, 'YYYYMMDD').valueOf();
                break;
            }
          }
          obj[key] = value;
        });
        tar.push(obj);
      });
    },
  }, //调用时要用this.$store.commit('molle/setKeyValue',{key,value})
  getters: {
    getValue: function(state) {
      return function(arg) {
        return {
          value: state[arg],
          arg: arg,
        };
      };
    },
    getFields: function(state) {
      console.log(state.realInfo);
      return function() {
        return Object.keys(state.realInfo);
      };
    },
    getLineData: function(state) {
      return function(arg) {
        let opts = Object.assign(
          {
            onlyTS: false,
          },
          arg
        );
        let r = _.cloneDeep(state.linedata);
        if (opts.onlyTS) {
          r.forEach((item) => {
            for (let key in item) {
              if (key != 'timestamp') {
                item[key] = 0;
              }
            }
          });
        }
        return r;
      };
    },
    getKlineParmas: function(state) {
      let def = _.pickBy(state.klineParmas, (v) => v !== null);
      return function(arg) {
        return Object.assign(def, arg);
      };
    },
  }, //调用时要用this.$store.getters['molle/getValue']
  actions: {
    ajaxKeyValue: function(state, { key, value }) {
      console.log();
      return Promise.resolve(200);
    },
    fetchKLineData: function(ctx, params) {
      let code = ctx.state.klineParmas.prod_code;
      let p = ctx.getters.getKlineParmas(params);
      return api3th
        .getKline(p)
        .then((res) => {
          ctx.commit('setHsDataFormatted', {
            hsData: res.data.candle[code],
            params: p,
          });
          return Promise.resolve(res);
        })
        .catch((err) => {
          console.error(err);
        })
        .finally((_) => {});
    },
    fetchRealData: function(ctx, {}) {
      let code = ctx.state.klineParmas.prod_code;
      let fields = Object.keys(ctx.state.realInfo);
      return api3th
        .获取股票实时信息({
          en_prod_code: [code],
          fields: fields,
        })
        .then((res) => {
          Object.assign(ctx.state.realInfo, res[0]);
          // console.log(res);
        })
        .catch((err) => {
          console.error(err);
        })
        .finally((_) => {});
    },
  },
};
